import axios from 'axios';
import Vue from 'vue'
import router from './router'

const http = axios.create({
    baseURL: process.env.VUE_APP_API_URL || '/admin/api',
    // baseURL: 'http://localhost:3001/admin/api'
})

http.interceptors.request.use(function (config) {
    const token = localStorage.getItem('token')
    if(token) {
        config.headers.Authorization = `Bearer ${token}`
    }
    return config;
}, function (error) {
    return Promise.reject(error);
});

http.interceptors.response.use((response) => {
    console.log('response :>> ', response);
    return response;
}, (error) => {
    const {status, data} = error.response
    const { message } = data || {}
    if(status >= 400 && message) {
        Vue.prototype.$message({
            type: 'error',
            message: message
        })
    }
    if(status === 401) {
        router.replace('/login')
    }
    return Promise.reject(error);
});

export default http